import random
import re

from django.contrib.auth.hashers import make_password
from rest_framework import serializers

from user.models import User


class UserModelSerializers(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'
        read_only_fields = ('uid',)
        extra_kwargs = {
            'password': {'required': False},
            'username': {'required': False},
            'avatar': {'required': False, 'default': '/static/imgs/avatar/default.jpg'},
            'sex': {'required': False, 'default': '男'}
        }

    def validate_phone(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError(detail='手机号格式不对', code=1000)
        return value

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data['password'])
        validated_data['username'] = '途牛' + str(random.randint(1000, 9999))
        return User.objects.create(**validated_data)
